﻿using System;
using Autofac;
using JetBrains.Annotations;
using UnityEngine;

namespace uMVP.AutofacExtends
{
    public static class LifetimeScopeExtends
    {
        /// <summary>
        /// 得到一个MonoBehaviour实例， 该MonoBehaviour会被AddComponent到参数gameObject下
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="gameObject">T这个MonoBehaviourAddComponent到这个参数下</param>
        /// <typeparam name="T">view视图对应的接口</typeparam>
        /// <returns>返回View视图实例</returns>
        public static T Resolve<T>([NotNull] this ILifetimeScope scope, [NotNull] GameObject gameObject)
        {
            if (scope == null) throw new ArgumentNullException(nameof(scope));
            
            return scope.Resolve<T>(new NamedParameter(ContainerBuilderExtends.GameObjectParameterName, gameObject));
        }

        public static object Resolve([NotNull] this ILifetimeScope scope, Type serviceType, [NotNull] GameObject gameObject)
        {
            if (scope == null) throw new ArgumentNullException(nameof(scope));
            
            return scope.Resolve(serviceType, new NamedParameter(ContainerBuilderExtends.GameObjectParameterName, gameObject));
        }
        
        public static T ResolveKeyed<T>([NotNull] this ILifetimeScope scope, object serviceKey, [NotNull] GameObject gameObject)
        {
            if (scope == null) throw new ArgumentNullException(nameof(scope));

            var parameter = new NamedParameter(ContainerBuilderExtends.GameObjectParameterName, gameObject);
            return scope.ResolveKeyed<T>(serviceKey, parameter);
        }
    }
}